studiocms
Version:
Astro Native CMS for AstroDB. Built from the ground up by the Astro community.
46 lines (45 loc) • 1.73 kB
JavaScript
import { oAuthProviders } from "studiocms:plugins/auth/providers";
import { Effect, genLogger } from "../../../../../effect.js";
const ProviderResponse = (error, status) => Effect.succeed(new Response(JSON.stringify({ error }), { status }));
async function promisifyFn(fn, context) {
return await fn(context);
}
const promisify = Effect.fn(function* (fn, context) {
return yield* Effect.tryPromise({
try: () => promisifyFn(fn, context),
catch: (error) => new Error(`Failed to execute API route: ${error}`)
});
});
const dispatchToAuthProvider = (context, handler, providers) => genLogger("OAuthAPIEffect.dispatchToAuthProvider")(function* () {
const provider = context.params.provider;
const matchedProvider = providers.find((p) => p.safeName === provider);
if (!matchedProvider) {
return yield* ProviderResponse("Provider not found", 404);
}
if (!matchedProvider.enabled) {
return yield* ProviderResponse("Provider is not configured", 403);
}
const handlerFn = matchedProvider[handler];
if (!handlerFn) {
return yield* ProviderResponse("Provider handler not found", 501);
}
return yield* promisify(handlerFn, context);
});
class OAuthAPIEffect extends Effect.Service()("OAuthAPIEffect", {
effect: genLogger("studiocms/routes/api/auth/[provider]/_shared")(function* () {
return {
initSession: (context) => dispatchToAuthProvider(context, "initSession", oAuthProviders),
initCallback: (context) => dispatchToAuthProvider(context, "initCallback", oAuthProviders)
};
})
}) {
// Export Dependency Providers
/**
* Main Dependencies Provider
*/
static Provide = Effect.provide(OAuthAPIEffect.Default);
}
export {
OAuthAPIEffect,
ProviderResponse
};